package com.happy3w.ssp.schoolmatehome.controller;

import com.happy3w.ssp.schoolmatehome.interceptor.AttributeKeys;
import com.happy3w.ssp.schoolmatehome.service.auth.TheUserDetail;
import com.happy3w.ssp.schoolmatehome.service.note.NoteReadDto;
import com.happy3w.ssp.schoolmatehome.service.note.NoteService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/note")
public class NoteController {
    private final NoteService noteService;

    @GetMapping("/{id}")
    public ResponseEntity<NoteReadDto> readNote(@PathVariable Long id,
                                                @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        Optional<NoteReadDto> noteOpt = noteService.readNote(id, userDetail.getUser());
        return noteOpt.map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PreAuthorize("hasRole('ROLE_NAMED')")
    @PutMapping("/{id}/favorite")
    public void markFavorite(@PathVariable Long id, @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        noteService.markFavorite(id, userDetail.getUser());
    }

    @PreAuthorize("hasRole('ROLE_NAMED')")
    @PutMapping("/{id}/unfavorite")
    public void unmarkFavorite(@PathVariable Long id, @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        noteService.unmarkFavorite(id, userDetail.getUser());
    }

    @PreAuthorize("hasRole('ROLE_NAMED')")
    @PutMapping("/{id}/collect")
    public void markCollect(@PathVariable Long id, @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        noteService.markCollect(id, userDetail.getUser());
    }

    @PreAuthorize("hasRole('ROLE_NAMED')")
    @PutMapping("/{id}/uncollect")
    public void unmarkCollect(@PathVariable Long id, @RequestAttribute(AttributeKeys.USER_DETAIL) TheUserDetail userDetail) {
        noteService.unmarkCollect(id, userDetail.getUser());
    }
}